package com.jhz.speedy.common.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import static android.content.Context.CONNECTIVITY_SERVICE;

/**
 * 网络工具
 * Created by JunHeZ on 2017/7/5.
 */
public class NetUtils {

    /**
     * 判断是否有网
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = cManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 判断是否有WIFI模块
     */
    public static boolean isWifiAvailable(Context context) {
        if (context != null) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * 判断是否有移动网络模块
     */
    public static boolean isMobileAvailable(Context context) {
        if (context != null) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }



    /**
     * 如需要网络监听广播，需要先注册
     */
    public static abstract class NetBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {   // 网络状态发生变化
                boolean isNetworkConnected = isNetworkConnected(context);
                onNetWorkStateChange(isNetworkConnected);
            }
        }

        public abstract void onNetWorkStateChange(boolean isNetConnected);
    }
}
